package com.wangjiang.mario.admin.web.admin.controller.v1;

import com.wangjiang.mario.admin.core.config.ServerConfig;
import com.wangjiang.mario.admin.common.base.BaseController;
import com.wangjiang.mario.admin.common.exception.NoFoundException;
import com.wangjiang.mario.admin.common.exception.PermissionException;
import com.wangjiang.mario.admin.common.rest.ResultGenerator;
import com.wangjiang.mario.admin.common.rest.entity.Result;
import com.wangjiang.mario.admin.common.util.CommonUtils;
import com.wangjiang.mario.admin.common.util.FileUtils;
import com.wangjiang.mario.admin.system.domain.components.ConfigComponent;
import com.wangjiang.mario.admin.system.domain.entity.FileEntity;
import com.wangjiang.mario.admin.system.domain.service.FileService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 资源上传下载控制类
 *
 * @Author wangjiang
 */
@RestController
@RequestMapping("/file")
@Api(value = "/file", tags = "资源上传下载控制类")
public class FileController extends BaseController<FileEntity> {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private ConfigComponent configComponent;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private FileService fileService;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        String fileName = fileService.saveFile(file);
        return ResultGenerator.genSuccessResult(fileName);
    }

    /**
     * 文件下载
     */
    @GetMapping("download/{filename}")
    public void fileDownload(
            @PathVariable String filename,
            HttpServletResponse response,
            HttpServletRequest request) {
        try{
            FileEntity fileEntity = fileService.getByFileName(filename);
            String realFileName = fileEntity.getOriginFilename();
            String rootPath = configComponent.getUploadRootPath();
            String filePath = rootPath  + filename;
            if(FileUtils.isExist(filePath) || !fileEntity.getHasResource()) {
                throw new NoFoundException("源文件已被删除");
            }
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (NoFoundException e) {
            logger.error(e.getMessage());
            throw new NoFoundException(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 文件预览
     */
    @GetMapping("view/{filename}")
    public void fileView(
            @PathVariable String filename,
            HttpServletResponse response) {
        try{
            FileEntity fileEntity = fileService.getByFileName(filename);
            // 找不到文件 将改为不跑出异常，该为返回404图片
//            if(CommonUtils.isNull(fileEntity)) {
//                throw new NoFoundException("没有该文件");
//            }
//            if(!fileEntity.getHasResource()) {
//                throw new NoFoundException("源文件已删除");
//            }

            if(CommonUtils.isNull(fileEntity) || fileEntity.getHasResource()) {
                // 记录状态
                logger.error("没有文件上传记录，或有源文件已删除记录");
                // 返回404图片
//                ClassPathResourceReader resourceReader = new ClassPathResourceReader("assets/images/404.png");
//                InputStream inputStream = resourceReader.getInpustream();
//                File file = File.c
                FileUtils.getFileFromJarResourceAndWriteBytes("assets/images/404.png", response.getOutputStream());
            } else {
                if(!FileUtils.isPicFile(fileEntity.getExtension())) {
                    throw new PermissionException("非图片文件，不可查看");
                }
                String rootPath = configComponent.getUploadRootPath();
                String filePath = rootPath + filename;
                response.setHeader("Content-Type", "image/jpeg");
                response.setCharacterEncoding("utf-8");
                response.setContentType("image/" + fileEntity.getExtension() );
                FileUtils.writeBytes(filePath, response.getOutputStream());
            }

        } catch (NoFoundException e) {
            logger.error(e.getMessage());
            throw new NoFoundException(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 文件删除
     */
    @DeleteMapping("/{filename}")
    public Result deleteFile(
            @PathVariable String filename
    ) {
        Boolean ret = fileService.deleteFileByFilename(filename);
        return ResultGenerator.genSuccessResult(ret);
    }




}
